package com.jaiky.imagespickers;

import com.jaiky.imagespickers.preview.FolderPopUpWindow;
import com.jaiky.imagespickers.utils.ResUtil;
import com.jaiky.imagespickers.utils.TimeUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.security.SystemPermission;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class ImageSelectorAbility extends Ability implements ImageDataSource.OnImagesLoadedListener, ImagePicker.OnImageSelectedListener, Component.ClickedListener {
    public static final int REQUEST_PERMISSION_STORAGE = 0x01;
    public static final int REQUEST_PERMISSION_CAMERA = 0x02;
    private ListContainer listContainer;
    private ToastDialog toast;
    private Button mBtnOk; // 确定按钮
    private ImagePicker imagePicker;
    private ImageAdapter listProvider;
    private int positionid = 0;
    private Component mFooterBar;     // 底部栏
    private Text mtvDir; // 显示当前文件夹
    private FolderAdapter mImageFolderAdapter; // 图片文件夹的适配器
    private FolderPopUpWindow mFolderPopupWindow; // ImageSet的PopupWindow
    private List<ImageFolder> mImageFolders; // 所有的图片文件夹
    private Text time_text;
    private DependentLayout toastView;

    @Override
    protected void onStart(Intent intent) {
        try {
            int color = getResourceManager().getElement(ResourceTable.Color_status_bar_color1).getColor();
            getWindow().setStatusBarColor(color);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_image_grid);
        imagePicker = ImagePicker.getInstance();
        imagePicker.setShowCamera(true); // 显示拍照按钮
        imagePicker.addOnImageSelectedListener(this);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_recycler);
        TableLayoutManager tableLayoutManager = new TableLayoutManager();
        tableLayoutManager.setColumnCount(3);
        listContainer.setLayoutManager(tableLayoutManager);
        time_text = (Text) findComponentById(ResourceTable.Id_time_text);
        // 确定按钮
        Image mBtnBack = (Image) findComponentById(ResourceTable.Id_btn_back);
        mBtnBack.setClickedListener(this);
        mBtnOk = (Button) findComponentById(ResourceTable.Id_btn_ok);
        mBtnOk.setClickedListener(this);
        mtvDir = (Text) findComponentById(ResourceTable.Id_tv_dir);
        mFooterBar = findComponentById(ResourceTable.Id_footer_bar);
        // 文件夹切换按钮
        Component mllDir = findComponentById(ResourceTable.Id_ll_dir);
        mllDir.setClickedListener(this);
        mImageFolderAdapter = new FolderAdapter(this, mImageFolders);
        this.listProvider = new ImageAdapter(this, null);
        onImageSelected(0, null, false);
        if (verifySelfPermission(SystemPermission.READ_USER_STORAGE) == IBundleManager.PERMISSION_GRANTED &&
                verifySelfPermission(SystemPermission.READ_MEDIA) == IBundleManager.PERMISSION_GRANTED &&
                verifySelfPermission(SystemPermission.MEDIA_LOCATION) == IBundleManager.PERMISSION_GRANTED) {
            new ImageDataSource(this, null, this);
        } else {
            requestPermissionsFromUser(new String[]{SystemPermission.READ_USER_STORAGE, SystemPermission.READ_MEDIA, SystemPermission.MEDIA_LOCATION}, REQUEST_PERMISSION_STORAGE);
        }
        listContainer.addScrolledListener(new Component.ScrolledListener() {
            @Override
            public void onContentScrolled(Component component, int i, int i1, int i2, int i3) {
                time_text.setVisibility(Component.VISIBLE);
                int firstVisibleItem = listContainer.getFirstVisibleItemPosition();
                int index = firstVisibleItem + 1 == listContainer.getItemProvider().getCount() ? listContainer.getItemProvider().getCount() - 1 : firstVisibleItem + 1;
                ImageItem image = (ImageItem) listContainer.getItemProvider().getItem(index);
                if (image != null) {
                    time_text.setText(TimeUtils.formatPhotoDate(image.addTime));
                }
            }
        });
        listContainer.setScrollListener(new ListContainer.ScrollListener() {
            @Override
            public void onScrollFinished() {
                time_text.setVisibility(Component.HIDE);
            }
        });
    }

    private void takePic() {
        imagePicker.takePicture(this);
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onStop() {
        imagePicker.removeOnImageSelectedListener(this);
        super.onStop();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();
        if (id == ResourceTable.Id_btn_ok) {
            if (imagePicker.getContainerAdapter() != null) {
                imagePicker.getContainerAdapter().refreshData(imagePicker.getSelectedImages());
            }
            Intent intent = new Intent();
            intent.setParam(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages());
            setResult(ImagePicker.RESULT_CODE_ITEMS, intent);  //多选不允许裁剪裁剪，返回数据
            terminateAbility();
        } else if (id == ResourceTable.Id_btn_back) {
            //点击返回按钮
            terminateAbility();
        } else if (id == ResourceTable.Id_ll_dir) {
            if (mImageFolders == null) {
                return;
            }
            //点击文件夹按钮
            createPopupFolderList();
            mImageFolderAdapter.setData(mImageFolders);  //刷新数据
            if (mFolderPopupWindow.isShowing()) {
                mFolderPopupWindow.hide();
            } else {
                mFolderPopupWindow.showOnCertainPosition(1, (int) 200, (int) 400);
                //默认选择当前选择的上一个，当目录很多时，直接定位到已选中的条目
                int index = mImageFolderAdapter.getSelectIndex();
                index = index == 0 ? index : index - 1;
                mFolderPopupWindow.setSelection(index);
            }
        }
    }

    /**
     * 创建弹出的ListView
     */
    private void createPopupFolderList() {
        mFolderPopupWindow = new FolderPopUpWindow(this, mImageFolderAdapter);
        mFolderPopupWindow.setSize(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        mFolderPopupWindow.setOnItemClickListener((listContainer, view, position, l) -> {
            mImageFolderAdapter.setSelectIndex(position);
            imagePicker.setCurrentImageFolderPosition(position);
            mFolderPopupWindow.hide();
            ImageFolder imageFolder = (ImageFolder) listContainer.getItemProvider().getItem(position);
            if (null != imageFolder) {
                if (position != 0) {
                    imagePicker.setShowCamera(false);
                } else {
                    imagePicker.setShowCamera(true);
                }
                listProvider.refreshData(imageFolder.images);
                mtvDir.setText(imageFolder.name);
            }
        });
        mFolderPopupWindow.setMargin(mFooterBar.getHeight());
        mFolderPopupWindow.setDialogListener(new BaseDialog.DialogListener() {
            @Override
            public boolean isTouchOutside() {
                mFolderPopupWindow.hide();
                return false;
            }
        });
    }


    @Override
    public void onImagesLoaded(List<ImageFolder> imageFolders) {
        this.mImageFolders = imageFolders;
        imagePicker.setImageFolders(imageFolders);
        if (imageFolders.size() == 0) {
            listProvider.refreshData(null);
        } else {
            Collections.reverse(imageFolders.get(0).images);
            listProvider.refreshData(imageFolders.get(0).images);
        }
        listContainer.setItemProvider(listProvider);
        mImageFolderAdapter.setData(imageFolders);
    }

    @Override
    public void onImageSelected(int position, ImageItem item, boolean isAdd) {
        positionid = imagePicker.isShowCamera() ? position - 1 : position;
        if (imagePicker.getSelectImageCount() > 0) {
            mBtnOk.setEnabled(true);
            if (imagePicker.getSelectLimit() == 1) {
                mBtnOk.setEnabled(false);
                mBtnOk.setText(ResUtil.getString(this, ResourceTable.String_ip_complete));
            } else {
                mBtnOk.setText(ResUtil.getString(this, ResourceTable.String_ip_select_complete, imagePicker.getSelectImageCount(), imagePicker.getSelectLimit()));
            }
        } else {
            mBtnOk.setText(ResUtil.getString(this, ResourceTable.String_ip_complete));
            mBtnOk.setEnabled(false);
        }
        for (int i = imagePicker.isShowCamera() ? 1 : 0; i < listProvider.getCount(); i++) {
            if (listProvider.getItem(i).uriSchema != null && listProvider.getItem(i).uriSchema.equals(item.uriSchema)) {
                positionid = imagePicker.isShowCamera() ? i - 1 : i;
                listProvider.notifyDataSetItemChanged(i);
                return;
            }
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                new ImageDataSource(this, null, this);
            } else {
                showToast("权限被禁止，无法选择本地图片");
            }
        } else if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                takePic();
            } else {
                showToast("权限被禁止，无法打开相机");
            }
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        try {
            super.onAbilityResult(requestCode, resultCode, data);
            if (data != null) {
                //从拍照界面返回
                //点击 X , 没有选择照片
                if (data.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS) != null) {
                    //说明是从裁剪页面过来的数据，直接返回就可以
                    if (resultCode == 10001) {
                        setResult(ImagePicker.RESULT_CODE_ITEMS, data);
                    } else {
                        ImageItem imageItem = new ImageItem();
                        imageItem.uriSchema = data.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);
                        imagePicker.addSelectedImageItem(0, imageItem, true, 1);
                        if (imagePicker.getContainerAdapter() != null) {
                            imagePicker.getContainerAdapter().refreshData(imagePicker.getSelectedImages());
                        }
                        Intent intent = new Intent();
                        intent.setParam(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages());
                        setResult(ImagePicker.RESULT_CODE_ITEMS, intent);  //多选不允许裁剪裁剪，返回数据
                    }
                }
                terminateAbility();
            } else {
                //如果是裁剪，因为裁剪指定了存储的Uri，所以返回的data一定为null
                if (resultCode == ImagePicker.RESULT_OK && requestCode == ImagePicker.REQUEST_CODE_TAKE) {
                    String path = imagePicker.getTakeImageFile().getAbsolutePath();
                    ImageItem imageItem = new ImageItem();
                    imageItem.uriSchema = path;
                    imagePicker.clearSelectedImages();
                    imagePicker.addSelectedImageItem(0, imageItem, true, 1);
                    Intent intent = new Intent();
                    intent.setParam(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages());
                    setResult(ImagePicker.RESULT_CODE_ITEMS, intent);   //单选不需要裁剪，返回数据
                    terminateAbility();
                }
            }
        } catch (Exception e) {
            terminateAbility();
        }
    }

    public void showToast(String content) {
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
        toast = new ToastDialog(this);
        toastView = (DependentLayout) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_faction_toast, null, false);
        Text toastText = (Text) toastView.findComponentById(ResourceTable.Id_text);
        toastText.setText(content);
        toast.setComponent(toastView);
        toast.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        toast.setTransparent(true);
        toast.setOffset(0, 100);
        toast.show();
    }

}
